import React from 'react';
import { dividerClass } from './style';
import type { DividerProps } from './types';
import { getAlignWidth } from './utils';

const Divider: React.FC<DividerProps> = (props) => {
  const {
    direction = 'horizontal',
    type = 'solid',
    align = 'center',
    margin = 12,
    className,
    style,
    children,
    bold = true,
    ...rest
  } = props;

  const classes = dividerClass('-', className, {
    [`direction-${direction}`]: !!direction,
    [`type-${type}`]: !!type,
    ['has-content']: !!children,
  });

  // 设置分割线 margin
  const marginStyle: React.CSSProperties = {};
  if (direction === 'horizontal') {
    marginStyle.marginTop = margin;
    marginStyle.marginBottom = margin;
  } else {
    marginStyle.marginLeft = margin;
    marginStyle.marginRight = margin;
  }

  // 设置分割线内容对齐方式
  const { left: leftWidth, right: rightWidth } = getAlignWidth(align);

  return (
    <div
      className={classes}
      style={{
        ...marginStyle,
        // 避免覆盖 style 属性
        ...style,
      }}
      {...rest}
    >
      {direction === 'horizontal' && children && (
        <>
          <div
            className={dividerClass('line')}
            style={{ maxWidth: leftWidth }}
          />
          <div className={dividerClass('content', { 'content-bold': bold })}>
            {children}
          </div>
          <div
            className={dividerClass('line')}
            style={{ maxWidth: rightWidth }}
          />
        </>
      )}
    </div>
  );
};

export default Divider;
